import { useEffect, useState } from "react"
import { SplashScreen, Stack } from "expo-router"
import { useFonts } from "@expo-google-fonts/space-grotesk"
import { KeyboardProvider } from "react-native-keyboard-controller"
import { initialWindowMetrics, SafeAreaProvider } from "react-native-safe-area-context"

import { useInitIAP } from "@/hooks/useInitIAP"
import { initI18n } from "@/i18n"
import {
  useInitialRootStore,
  useStores,
  RootStoreProvider,
  _rootStore,
} from "@/models/helpers/useStores"
import { ThemeProvider } from "@/theme/context"
import { customFontsToLoad } from "@/theme/typography"
import { loadDateFnsLocale } from "@/utils/formatDate"

SplashScreen.preventAutoHideAsync()

if (__DEV__) {
  // Load Reactotron configuration in development. We don't want to
  // include this in our production bundle, so we are using `if (__DEV__)`
  // to only execute this in development.
  require("@/devtools/ReactotronConfig")
}

export default function Root() {
  const [fontsLoaded, fontError] = useFonts(customFontsToLoad)
  const [isI18nInitialized, setIsI18nInitialized] = useState(false)
  const { userStore, agentsStore } = useStores()
  const { rehydrated } = useInitialRootStore(() => {
    // This runs after the root store has been initialized and rehydrated.
    // If your initialization scripts run very fast, it's good to show the splash screen for just a bit longer to prevent flicker.
    // Slightly delaying splash screen hiding for better UX; can be customized or removed as needed,
    // Note: (vanilla Android) The splash-screen will not appear if you launch your app via the terminal or Android Studio. Kill the app and launch it normally by tapping on the launcher icon. https://stackoverflow.com/a/69831106
    // Note: (vanilla iOS) You might notice the splash-screen logo change size. This happens in debug/development mode. Try building the app for release.
    // setTimeout(hideSplashScreen, 500)
  })

  useEffect(() => {
    initI18n()
      .then(() => setIsI18nInitialized(true))
      .then(() => loadDateFnsLocale())
  }, [])

  useEffect(() => {
    if (!rehydrated) {
      return
    }
    if (userStore.uuid) {
      userStore.refreshSession().then((res) => {
        console.log("refreshSession", res)
        userStore.fetchProfile().then((r) => {
          console.log("fetchProfile", r)
        })
      })
    } else {
      userStore.visitorLogin().then((res) => {
        console.log("visitorLogin", res)
      })
    }

    agentsStore.fetchModels()
  }, [rehydrated])

  useInitIAP()

  const loaded = fontsLoaded && isI18nInitialized

  useEffect(() => {
    if (fontError) throw fontError
  }, [fontError])

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync()
    }
  }, [loaded])

  if (!loaded) {
    return null
  }

  return (
    <RootStoreProvider value={_rootStore}>
      <SafeAreaProvider initialMetrics={initialWindowMetrics}>
        <ThemeProvider initialContext={"light"}>
          <KeyboardProvider>
            <Stack screenOptions={{ headerShown: false }}>
              <Stack.Screen
                name="appLoading"
                options={{
                  presentation: "transparentModal",
                  animation: "none",
                }}
              />
            </Stack>
          </KeyboardProvider>
        </ThemeProvider>
      </SafeAreaProvider>
    </RootStoreProvider>
  )
}
